package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.GroupRelationship;
import cn.stylefeng.guns.modular.robot.service.GroupRelationshipService;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class CmdQzlist extends AbstractCmd {

    @Resource
    private GroupRelationshipService groupRelationshipService;
    @Resource
    private GroupService groupService;

    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        Long chatId = update.getMessage().getChatId();
        List<GroupRelationship> groupRelationships = groupRelationshipService.lambdaQuery()
                .eq(GroupRelationship::getReceiveGroupId, chatId)
                .list();
        if (CollectionUtils.isEmpty(groupRelationships)) {
            RobotUtils.sendText(chatId, "当前群无下游群", bot);
            return;
        }
        Set<Long> groupIds = groupRelationships.stream().map(GroupRelationship::getSendGroupId).collect(Collectors.toSet());
        List<Group> groups = groupService.lambdaQuery()
                .in(Group::getTgGroupId, groupIds)
                .list();
        if(CollectionUtils.isEmpty(groups)){
            return;
        }
        StringBuilder sb = new StringBuilder();
        for (Group group : groups) {
            sb.append(group.getName()).append("群 编号#").append(group.getId()).append("\n");
        }
        RobotUtils.sendText(chatId, sb.toString(), bot);
    }

    @Override
    public String getCmdName() {
        return "QZLIST";
    }

    @Override
    public String getDescribe() {
        return "qzlist                         查询下游群列表\n";
    }
}
